import React, { PureComponent } from 'react';
import {
  Card,
  Form,
  Col,
  Row,
  Input,
  Select,
  message,
  Button,
  Checkbox,
  Table,
  Divider,
  Transfer,
} from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import { transferOption } from '@/utils/common';
import styles from './index.less';
import difference from 'lodash/difference';
import Ellipsis from '@/components/Ellipsis';

const fieldLabels = {
  code: '钥匙车型组编码',
  name: '钥匙车型组名称',
  brandCode: '品牌',
  seriesCode: '车系',
  remarks: '备注',
};

const TableTransfer = ({ leftColumns, rightColumns, loading, ...restProps }) => (
  <Transfer {...restProps} showSelectAll={false}>
    {({
      direction,
      filteredItems,
      onItemSelectAll,
      onItemSelect,
      selectedKeys: listSelectedKeys,
      disabled: listDisabled,
    }) => {
      const columns = direction === 'left' ? leftColumns : rightColumns;

      const rowSelection = {
        getCheckboxProps: (item) => ({
          disabled: listDisabled || item.disabled,
        }),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter((item) => !item.disabled)
            .map(({ key }) => key);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys, selected);
        },
        onSelect({ key }, selected) {
          onItemSelect(key, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      return (
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={filteredItems}
          size="small"
          style={{ pointerEvents: listDisabled ? 'none' : null }}
          rowClassName={(record) => {
            return record.disabled ? styles['disabled-row'] : '';
          }}
          onRow={({ key, disabled: itemDisabled }) => ({
            onClick: () => {
              if (itemDisabled || listDisabled) return;
              onItemSelect(key, !listSelectedKeys.includes(key));
            },
          })}
          pagination={false}
          scroll={{ y: 220 }}
          loading={loading}
        />
      );
    }}
  </Transfer>
);
const leftTableColumns = [
  {
    dataIndex: 'modelCode',
    title: '车型编码',
  },
  {
    dataIndex: 'groupCode',
    title: '钥匙车型组',
    width: 125,
    render: (val) => (
      <Ellipsis length={12} tooltip>
        {val}
      </Ellipsis>
    ),
  },
];
const rightTableColumns = [
  {
    dataIndex: 'modelCode',
    title: '车型编码',
  },
];

const mapStateToProps = (state) => ({
  basedata: state.basedata,
  digitalKeyModelsGroup: state.digitalKeyModelsGroup,
  loading: state.loading.effects['digitalKeyModelsGroup/getFetchPage'],
  menu: state.menu,
});
class DigitalKeyModelsGroupAdd extends PureComponent {
  state = {
    title: '',
    brandOptions: [],
    seriesOptions: [],
    targetKeys: [],
    modelOriginData: [],
    buttonLoading: false,
    dataLoading: false,
  };
  formRef = React.createRef();
  componentWillMount() {}
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'basedata/brandFetch',
      callback: (res) => this.setState({ brandOptions: res?.data }),
    });
  }
  onBrandSelect = (value) => {
    const { dispatch } = this.props;
    this.setState({ seriesOptions: [], brandCode: value, modelOriginData: [], seriesCode: null });
    this.formRef.current?.setFieldsValue({
      seriesCode: null,
    });
    if (!value) {
      return;
    }
    dispatch({
      type: 'basedata/seriesList',
      payload: { brandId: value },
      callback: (response) => {
        if (response) {
          this.setState({
            seriesOptions: response.filter((item) => item.code !== ''),
          });
        }
      },
    });
  };
  onSeriesSelect = (value) => {
    const { dispatch } = this.props;
    const { brandCode } = this.state;

    this.setState({
      modelOriginData: [],
      seriesCode: value,
      dataLoading: true,
    });
    if (!value) {
      return;
    }
    const params = {
      brandCode,
      seriesCode: value,
    };
    dispatch({
      type: 'digitalKeyModelsGroup/getData',
      payload: { url: '/bluetooth/key/group/modelList', ...params },
      callback: (response) => {
        this.setState({ dataLoading: false });
        if (response) {
          this.setState({
            modelOriginData: response.data?.map((item) => {
              return {
                ...item,
                key: item.modelCode,
                disabled: !!item.groupCode,
              };
            }),
          });
        }
      },
    });
  };
  onTransferChange = (nextTargetKeys) => {
    this.setState({ targetKeys: nextTargetKeys });
  };

  goBack = () => {
    router.push({
      pathname: '/bluetoothCloseControl/digitalKeyModelsGroup',
    });
  };
  save = () => {
    const { dispatch } = this.props;
    const { targetKeys } = this.state;
    this.formRef.current.validateFields().then((values) => {
      //  if (err) return;
      if (targetKeys.length < 1) {
        message.error('请选择关联的车型');
        return;
      }
      const params = {
        ...values,
        code: values.code?.toString().trim(),
        name: values.name?.toString().trim(),
        vehicleModels: targetKeys,
      };

      // 数据校验通过开始设置按钮loading
      this.setState({ buttonLoading: true });
      dispatch({
        type: 'digitalKeyModelsGroup/postObjWithRes',
        payload: {
          url: '/bluetooth/key/group/add',
          ...params,
        },
        callback: (response) => {
          this.setState({ buttonLoading: false });
          if (response.statusCode === '0') {
            message.success('保存成功');
            this.goBack();
          } else {
            // message.error(response.statusMessage);
          }
        },
      });
    });
  };
  render() {
    const { form, dispatch } = this.props;
    const { buttonLoading, brandOptions, seriesOptions, modelOriginData, targetKeys, dataLoading } =
      this.state;
    return (
      <div>
        <Card title="创建数字钥匙车型组" bordered={false} className={styles['container']}>
          <Form layout="horizontal" className={styles['content-wrapper']} ref={this.formRef}>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.code}
                  name="code"
                  rules={[{ required: true, message: '请输入钥匙车型组编码', whitespace: true }]}
                >
                  <Input placeholder="请输入钥匙车型组编码" />
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.name}
                  name="name"
                  rules={[{ required: true, message: '请输入钥匙车型组名称', whitespace: true }]}
                >
                  <Input placeholder="请输入钥匙车型组名称" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.brandCode}
                  name="brandCode"
                  rules={[{ required: true, message: '请选择品牌' }]}
                >
                  <Select
                    allowClear={false}
                    placeholder="请选择品牌"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    onChange={this.onBrandSelect}
                  >
                    {transferOption(brandOptions, ['brandCode', 'brandName'])}
                  </Select>
                </Form.Item>
              </Col>
              <Col lg={8} md={12} sm={24}>
                <Form.Item
                  label={fieldLabels.seriesCode}
                  name="seriesCode"
                  rules={[{ required: true, message: '请选择车系' }]}
                >
                  <Select
                    allowClear={false}
                    placeholder="请选择车系"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    onChange={this.onSeriesSelect}
                  >
                    {transferOption(seriesOptions, ['code', 'name'])}
                  </Select>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={8} md={12} sm={24}>
                <Form.Item label={fieldLabels.remarks} name="remarks">
                  <Input placeholder="请输入备注" />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col lg={20} md={20} sm={24}>
                <Card
                  title={
                    <p>
                      <span className={styles['required-mark']}>*</span>
                      <span className={styles['sub-title']}>选择关联车型</span>
                    </p>
                  }
                >
                  <TableTransfer
                    dataSource={modelOriginData}
                    titles={['所有车型编码', '包含车型编码']}
                    targetKeys={targetKeys}
                    showSearch
                    searchPlaceholder="请输入车型编码"
                    onChange={this.onTransferChange}
                    filterOption={(inputValue, item) => item.modelCode.indexOf(inputValue) !== -1}
                    leftColumns={leftTableColumns}
                    rightColumns={rightTableColumns}
                    loading={dataLoading}
                    listStyle={{
                      minWidth: 380,
                    }}
                  />
                  {/* <Transfer
                    rowKey={(record) => record.value}
                    dataSource={this.props.mockData}
                    titles={["未关联", "已关联"]}
                    showSearch
                    filterOption={(input, option) =>
                      option?.label?.indexOf(input) >= 0
                    }
                    listStyle={{
                      width: 360,
                      height: 500,
                    }}
                    searchPlaceholder="关键字"
                    targetKeys={targetKeys.split(",")}
                    operations={["绑定", "解绑"]}
                    notFoundContent="列表为空"
                    onChange={this.handleChange}
                    onSelectChange={this.handleSelectChange}
                    onScroll={this.handleScroll}
                    render={(item) => item.label}
                    footer={this.renderFooter}
                  /> */}
                </Card>
              </Col>
            </Row>
          </Form>

          <Divider></Divider>
          <Row gutter={24} type="flex" justify="end" className={styles['footer']}>
            <Col span={8} justify="right">
              <div className={styles['btns']}>
                <Button key="back" size="small" onClick={this.goBack}>
                  取消
                </Button>
                <Button
                  loading={buttonLoading}
                  key="submit"
                  type="primary"
                  size="small"
                  onClick={this.save}
                >
                  确认
                </Button>
              </div>
            </Col>
          </Row>
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(DigitalKeyModelsGroupAdd);
